"""This module provides zhuhu small"""
import json
import os
import time
import re
import platform
import datetime
from playwright.sync_api import sync_playwright
from playwright.sync_api import Page
from auto.sleep.data import go_to_sleep
from auto.sleep.data import get_pitcute
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers.cron import CronTrigger
########################################################################
class CMyWeiBo:
    """
    This class represents a GetupHabit.

    Parameters:
    - save_picture_path (str): The path to save pictures.
    - default_picture_path (str): The default path for pictures.
    """
    def __init__(self,cookies_path: str, login_url: str, upload_picture_url: str, upload_mp4_url: str):
        self.cookies_path = cookies_path
        self.login_url = login_url
        self.upload_picture_url = upload_picture_url
        self.upload_mp4_url = upload_mp4_url
        # playwright 部分
        self.browser = None
        # 想法 ---喜欢
        self.user_list = None
        self.context = None
        print("create CMyWeiBo")

    def __del__(self):
        print("CMyWeiBo is being destroyed")

    def upload_picture(self, picture_path_list: str, habit_name:str, habit_detail:str):
        """
          upload_picture
        """
        with sync_playwright() as playwright:
            display_headless = False
            sys = platform.system()
            if sys == "Linux":
              display_headless = True
              self.browser = playwright.chromium.launch(headless=display_headless)
            else:
                self.browser = playwright.chromium.launch(channel="chrome",headless=display_headless)
            login_page = self.login_or_restore_cookies()
            print("login_or_restore_cookies")
            self.msg_up_load(login_page, picture_path_list, habit_name,habit_detail)
            self.browser.close()
    
    def login_or_restore_cookies(self) -> Page:
        """
          登录
        """
        # https://useragent.buyaocha.com/
        #  https://http.dev/user-agent
        userAgent ="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36"
        sys = platform.system()
        if sys == "Linux":
            userAgent='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36'
        elif sys == "Darwin":
           # chrome://version/
           userAgent='ozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36'
        
        self.context = self.browser.new_context(user_agent=userAgent)
        #browser.new_context() 创建一个新的浏览器上下文。它不会与其他浏览器上下文共享 cookies/缓存。
        #context之间是相互隔离的，可以理解为轻量级的浏览器实例--打开了多个浏览器
        
        if os.path.exists(self.cookies_path):
            with open(self.cookies_path, 'r',encoding='utf-8') as f:
                cookies = json.load(f)

            current_time = datetime.datetime.now()
            # 延长1天
            extended_time = current_time + datetime.timedelta(days=1)
            # 获取时间戳（精确到秒）
            timestamp = int(extended_time.timestamp())
            for cookie in cookies:
                 if cookie['name'] == 'WBPSESS' or cookie['name'] == 'PC_TOKEN' or cookie['name'] == 'SUB':
                    cookie['expires'] = timestamp
                 if cookie['name'] == 'ALF' or cookie['name'] == 'SUBP' or cookie['name'] == 'SUBP' or cookie['name'] == 'SCF':
                    cookie['expires'] = timestamp
                    
            self.context.add_cookies(cookies)
            time.sleep(3)
        # 先添加add_cookies
        # 每个浏览器上下文可以承载多个页面
        # Each BrowserContext can have multiple pages. 
        # A Page refers to a single tab or a popup window within a browser context. 
        # It should be used to navigate to URLs and interact with the page content.
        page = self.context.new_page()
        page.goto(self.login_url)

        if os.path.exists(self.cookies_path):
            pass
        else:
            # 扫名二维码登录 需要人工处理
            # 扫名二维码登录 需要人工处理
            # 扫名二维码登录 需要人工处理
            time.sleep(45)
            cookies = page.context.cookies()
            with open(self.cookies_path, 'w',encoding='utf-8') as f:
                f.write(json.dumps(cookies))
        print("login_or_restore_cookies")
        return page
    
    def msg_up_load(self, page: Page, picture_path_list,habit_name:str, habit_detail:str):
        """
         发布微头条
        """
        page.goto(self.upload_picture_url,timeout=60000)
        print(f"open  {self.upload_picture_url}")
        page.locator("form img").first.click()
        page.wait_for_timeout(5000)

        print("开始上传图片")
        with page.expect_file_chooser() as fc_info:
            page.get_by_label("本地图片").locator("span").nth(2).click()
        file_chooser = fc_info.value
        file_chooser.set_files(picture_path_list)
        page.wait_for_timeout(30000)
        page.get_by_role("button", name="确 认").click()
        page.wait_for_timeout(2000)

        msg = habit_name + "\r\n"
        msg += habit_detail
        page.get_by_placeholder("有什么新鲜事想告诉大家").fill(msg)
        page.wait_for_timeout(3000)

        

        page.get_by_role("button").nth(1).click()
        print("发送")
        page.wait_for_timeout(20000)

    def msg_up_tuwen(self, page: Page, picture_path_list,habit_name:str, habit_detail:str):
        """
         图文：
         # playwright codegen https://baijiahao.baidu.com/builder/rc/edit?type=news
        """
        page.goto(self.upload_picture_url)
        page.wait_for_timeout(10000)
        print(f"open  {self.upload_picture_url}")
        page.get_by_placeholder("请输入标题（5 - 30字）").fill(habit_name)
        page.wait_for_timeout(10)

        
        page.locator("div").filter(has_text=re.compile(r"^添加图片$")).click()
        print("开始上传图片")
        page.wait_for_timeout(1000)

        with page.expect_file_chooser() as fc_info:
            page.get_by_text("本地上传").click()
        file_chooser = fc_info.value
        file_chooser.set_files(picture_path_list)
        page.wait_for_timeout(20000)
        page.get_by_role("button", name="确 认").click()
        page.wait_for_timeout(1000)
        
        page.mouse.down()
        page.mouse.down()
        page.mouse.down()
        page.wait_for_timeout(1000)
        page.get_by_label("自动").check()
        page.wait_for_timeout(1000)


        page.get_by_role("button").first.click()
        print("发送")
        page.wait_for_timeout(10000000)

###############################################################

def interface_auo_upload_msg_baijia(file_path_list:str,habit_name :str,habit_detail :str):
    """
      对外调用接口
       playwright codegen https://baijiahao.baidu.com
    """
    print("https://baijiahao.baidu.com/")
    sys = platform.system()
    login_url = "https://baijiahao.baidu.com/"
    upload_picture_url = "https://baijiahao.baidu.com/builder/rc/edit?type=events"
    upload_mp4_url = "https://baijiahao.baidu.com/builder/rc/edit?type=events"
    if sys == "Windows":
        cookies_path = r"D:\mp4\etc\baijia_small.json"
    elif sys == "Darwin":
        cookies_path = r"/Users/wangchuanyi/mp4/etc/baijia_small.json"
    else:
        cookies_path = r"/root/bin/baijia_small.json"
    autoupload = CMyWeiBo(cookies_path, login_url, upload_picture_url,upload_mp4_url)
    with sync_playwright() as playwright:
        display_headless = False
        sys = platform.system()
        if sys == "Linux":
            display_headless = True
            browser = playwright.chromium.launch(headless=display_headless)
        else:
            browser = playwright.chromium.launch(channel="chrome",headless=display_headless)
        autoupload.browser = browser
        login_page = autoupload.login_or_restore_cookies()
        # 发布微头条
        try:
            autoupload.msg_up_load(login_page, file_path_list, habit_name,habit_detail)
            autoupload.browser.close()
        except Exception as err:
            print(f"Unexpected {err=}, {type(err)=}")

def interface_auo_upload_msg_tuji(file_path_list:str,habit_name :str,habit_detail :str):
    """
      对外调用接口
       playwright codegen https://baijiahao.baidu.com/builder/rc/edit?type=gallery
    """
    print("https://baijiahao.baidu.com/")
    sys = platform.system()
    login_url = "https://baijiahao.baidu.com/"
    upload_picture_url = "https://baijiahao.baidu.com/builder/rc/edit?type=gallery"
    upload_mp4_url = "https://baijiahao.baidu.com/builder/rc/edit?type=gallery"
    if sys == "Windows":
        cookies_path = r"D:\mp4\etc\baijia_small.json"
    elif sys == "Darwin":
        cookies_path = r"/Users/wangchuanyi/mp4/etc/baijia_small.json"
    else:
        cookies_path = r"/root/bin/baijia_small.json"
    autoupload = CMyWeiBo(cookies_path, login_url, upload_picture_url,upload_mp4_url)
    with sync_playwright() as playwright:
        display_headless = False
        sys = platform.system()
        if sys == "Linux":
            display_headless = True
            browser = playwright.chromium.launch(headless=display_headless)
        else:
            browser = playwright.chromium.launch(channel="chrome",headless=display_headless)
        autoupload.browser = browser
        login_page = autoupload.login_or_restore_cookies()
        # 发布微头条
        try:
            autoupload.msg_up_tuwen(login_page, file_path_list, habit_name,habit_detail)
            autoupload.browser.close()
        except Exception as err:
            print(f"Unexpected {err=}, {type(err)=}")
            autoupload.browser.close()
###################################################
def future_for_sleep():
    """
      每天写50字产品理解输出，10行代码
    """
    habit_detail = go_to_sleep.interface_go_to_sleep()
    random_images = get_pitcute.interface_get_three_pic(3)
    habit_name = "21点远离手机提醒"
    # 格式化为 年-月-日
    formatted_date = datetime.datetime.now().strftime('%Y-%m-%d')
    habit_name = formatted_date + " " + habit_name

    try:
        interface_auo_upload_msg_baijia(random_images, habit_name, habit_detail)
        #interface_auo_upload_msg_tuji(random_images, habit_name, habit_detail)

    except Exception as err:
        print(f"Unexpected {err=}, {type(err)=}")
if __name__ == '__main__':
    future_for_sleep()
    job_defaults = {
        'coalesce': False,
        'max_instances': 1
    }
    # 调度器组件
    backsched = BlockingScheduler(job_defaults=job_defaults, timezone='Asia/Shanghai')
    backsched.add_job(future_for_sleep, CronTrigger.from_crontab("0 1 * * *"), id="get_up")
    backsched.start()